﻿using System;
using System.Text;
using System.Threading;
using Bll;
using Common;
using CommonModel.Config;
using RabbitMQ.Client;

namespace MqConsumer
{
    class Program
    {
        private static string messageQueue = "Test.One";
        private static IConnection Connection { get; set; }

        static void Main(string[] args)
        {
            try
            {
                if (Connection == null || !Connection.IsOpen)
                {
                    Connection = GetConnection();
                }
                if (Connection != null && Connection.IsOpen)
                {
                    using (var channel = Connection.CreateModel())
                    {
                        channel.QueueDeclare(messageQueue, true, false, false, null);//持久化
                        channel.BasicQos(0, 1, false); //分发机制：每次分发一个消息
                        var consumer = new QueueingBasicConsumer(channel); //建立消费者
                        channel.BasicConsume(messageQueue, false, consumer);//设置为消息响应模式：需配合手动应答

                        while (true)
                        {
                            var ea = consumer.Queue.Dequeue();//获取消息
                            string message = Encoding.UTF8.GetString(ea.Body);
                            Console.WriteLine("消费消息中...：\r\n"+message);
                            Thread.Sleep(1000*3);
                            //result = DealMessage(message);//处理消息
                            Console.WriteLine("消费消息结束");
                            channel.BasicAck(ea.DeliveryTag, false); //手动应答
                        }
                    }
                }
                else
                {
                    LogHelper.Debug("获取Mq链接为空或者非打开状态");
                    Console.WriteLine("获取Mq链接为空或者非打开状态");
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("报错："+ex.Message);
            }
            Console.WriteLine("程序已停止运行，按任意键结束");
            Console.ReadKey();
        }

        #region 私有方法
        /// <summary>
        /// 获取一个Mq链接
        /// </summary>
        /// <returns></returns>
        private static IConnection GetConnection()
        {
            IConnection connection = null;

            var connectionFactory = new ConnectionFactory();
            connectionFactory.HostName = MqConfig.HostName;
            connectionFactory.UserName = MqConfig.UserName;
            connectionFactory.Password = MqConfig.Password;
            //connectionFactory.Port = "";
            connection = connectionFactory.CreateConnection();
            connection.AutoClose = false;

            return connection;
        }
        #endregion


    }
}
